import App from '../App'
var requestUrl = App.globalData.requestUrl
var token = uni.getStorageSync('token')
var cookieKey = uni.getStorageSync('cookieKey')
var cookieValue = uni.getStorageSync('cookieValue')
console.log('cookieKey',cookieKey);
console.log('cookieValue',cookieValue);
var request = (url, data, method = 'POST') => {
	uni.showLoading({
		title: "加载中..."
	})
	return new Promise((resolve, reject) => {
		uni.request({
			url: requestUrl + url,
			method: method,
			data: data,
			header: {
				'Content-Type': 'application/json',
				'Authorization': `Bearer ${cookieValue}`,
				'Access-Control-Allow-Headers': 'token',
				// 'Cookie':`cookieKey=${cookieValue}`
			},
			withCredentials:true,
			success: (res) => {
				// 获取所有响应头
				const headers = res.header;
				// console.log("headers",headers);
				// 获取 Set-cookie 头
				const setCookie = headers['Set-Cookie'] || headers['set-cookie'];
				console.log("setCookie",setCookie);
				if (setCookie) {
					const array = setCookie.split('=');
					console.log('array',array);
					uni.setStorage({
						key:'cookieKey',
						data:array[0],
					})
					uni.setStorage({
						key:'cookieValue',
						data:array[1],
					})
					// 解析 Set-Cookie 头中的 expires 信息
					// const expiresMatch = setCookie.match(/expires=([^;]+)/i);
					// if (expiresMatch && expiresMatch[1]) {
						// const expiresDate = new Date(expiresMatch[1]);
						// console.log('cookie 过期时间:', expiresDate);
						// 计算剩余时间
						// const now = new Date();
						// const timeLeft = expiresDate - now;
						// console.log('剩余时间(秒):', timeLeft / 1000);
					// } else {
						// console.log('未找到 expires 信息');
					// }
					
				} else {
					// console.log('未找到Set-cookie 头');
				}
				resolve(res.data)
				uni.hideLoading()
			},
			fail(err) {
				reject(err)
			}
		})
	})
}
export default {
	request
}